import cv2
import numpy as np
import time
import subprocess
from datetime import datetime
from ObjectWrapper import *
from Visualize import *
from musicmap import music_dict

def getObjects():
    ret,img = cap.read()
    start = datetime.now()

    results = detector.Detect(img)

    end = datetime.now()
    elapsedTime = end-start

    print ('total time is " milliseconds', elapsedTime.total_seconds()*1000)
    return results

def getCollision():
# 转换为HSV
    ret,img = cap.read()
    hue_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# 用颜色分割图像
    low_range = np.array([0, 123, 100])
    high_range = np.array([5, 255, 255])
    th = cv2.inRange(hue_image, low_range, high_range)

# 形态学运算，膨胀
    dilated = cv2.dilate(th, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=2)

# Hough Circle
    circles = cv2.HoughCircles(dilated, cv2.HOUGH_GRADIENT, 1, 100, param1=15, param2=7, minRadius=10, maxRadius=20)

# 提取与绘制
    img = Visualize(img,detect_results)
    results = []
    
    if circles is not None:
        x, y, radius = circles[0][0]
        center = (x, y)
        cv2.circle(img, center, radius, (0, 255, 0), 2)
        for i,r in enumerate(detect_results):
            if x>=r.left and x<= r.right and y>=r.top and y <= r.bottom:
                results.append(i)
    cv2.imshow('result', img)
    return results

def setSound():
    #粗糙地写一下
    l = list(range(len(detect_results)))
    return l

def play(sound):
    print(sound)
    freq = music_dict[sound]
    proc = subprocess.Popen(['speaker-test', '--frequency', str(freq), '--test', 'sine'],
                            stdout=subprocess.DEVNULL)
    try:
        proc.wait(timeout=0.3)
    except subprocess.TimeoutExpired:
        pass
    finally:
        proc.kill()


network_blob='graph'
detector = ObjectWrapper(network_blob)

cap = cv2.VideoCapture(-1)

detect_results = getObjects()
sound_list = setSound()
inbox = False
last_collision = []
while True:
    results = getCollision()
    for r in results:
        if not r in last_collision:
            play(sound_list[r])
        
    last_collision = results
    
    #cv2.waitKey(0)
    key = cv2.waitKey(20) & 0xFF
    if key == ord('q'):
        break
